package com.woniuxy.kaer.tenants.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.kaer.commons.util.OSSUtil;
import com.woniuxy.kaer.tenants.entity.ApplyAttachments;
import com.woniuxy.kaer.tenants.entity.Settled;
import com.woniuxy.kaer.tenants.mapper.ApplyAttachmentsMapper;
import com.woniuxy.kaer.tenants.mapper.SettledMapper;
import com.woniuxy.kaer.tenants.param.TenantsApplyAttachmentsParam;
import com.woniuxy.kaer.tenants.service.ApplyAttachmentsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.geom.QuadCurve2D;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 程诗洋
 * @since 2025年02月17日
 */
@Service
public class ApplyAttachmentsServiceImpl extends ServiceImpl<ApplyAttachmentsMapper, ApplyAttachments> implements ApplyAttachmentsService {

    @Resource
    private OSSUtil ossUtil;
    @Resource
    private ApplyAttachmentsMapper applyAttachmentsMapper;
    @Resource
    private SettledMapper settledMapper;


    @Override
    public void submitApplyAttachments(TenantsApplyAttachmentsParam param) throws Exception {
        //BookType bookType = bookTypeMapper.selectById(param.getTypeId());
        byte[] bytes = new byte[4];
        param.getAttachmentUrl().getInputStream().read(bytes);
        if(!ossUtil.isPdf(bytes)){
            throw new Exception("文件格式不正确");
        }
        Settled settled = settledMapper.selectById(param.getSettledId());
        if(null==settled){
            throw new Exception("申请记录不存在");
        }
        String s = FileUtil.extName(param.getAttachmentUrl().getOriginalFilename());
        String s1 = UUID.randomUUID().toString();
        String AttachmentUrl = ossUtil.uploadFile(param.getAttachmentUrl().getInputStream(), s1 + "." + s, "guojiandong");
        ApplyAttachments applyAttachments = BeanUtil.toBean(param, ApplyAttachments.class);
        applyAttachments.setAttachmentUrl(AttachmentUrl);
        //服务器地址填写的是oss存储空间名
        applyAttachments.setServiceName("guojiandong");
        applyAttachmentsMapper.insert(applyAttachments);
    }

    @Override
    public ApplyAttachments getApplyAttachments(Integer settleId) throws Exception {
        QueryWrapper<ApplyAttachments> applyAttachmentsQueryWrapper = new QueryWrapper<>();
        applyAttachmentsQueryWrapper.eq("settled_id",settleId);
        ApplyAttachments applyAttachments = applyAttachmentsMapper.selectOne(applyAttachmentsQueryWrapper);
        return applyAttachments;
    }
}
